﻿using System;
using System.Collections.Generic;
using System.Text;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace MedicalDB.Export
{
    class PDFGenerator
    {
        public void DefineStyles(Document document)
        {
            // Get the predefined style Normal.
            Style style = document.Styles["Normal"];
            // Because all styles are derived from Normal, the next line changes the
            // font of the whole document. Or, more exactly, it changes the font of
            // all styles and paragraphs that do not redefine the font.
            style.Font.Name = "Times New Roman";

            // Heading1 to Heading9 are predefined styles with an outline level. An outline level
            // other than OutlineLevel.BodyText automatically creates the outline (or bookmarks)
            // in PDF.

            style = document.Styles["Heading1"];
            style.Font.Name = "Tahoma";
            style.Font.Size = 16;
            style.Font.Bold = true;
            style.Font.Color = Colors.DarkBlue;
            style.ParagraphFormat.PageBreakBefore = true;
            style.ParagraphFormat.SpaceAfter = 6;

            style = document.Styles["Heading2"];
            style.Font.Size = 10;
            style.ParagraphFormat.SpaceAfter = 10;
            style.ParagraphFormat.SpaceBefore = 30;


            style.ParagraphFormat.PageBreakBefore = false;

            //style.ParagraphFormat.
            style.Font.Size = 14;
            style.Font.Bold = true;
            style.Font.Color = Colors.Purple;


        }

        public void AddTitle(Document document, string title, int leftindent)
        {
            Section section = document.LastSection;
            Paragraph paragraph = section.AddParagraph(title, "Heading1");
            paragraph.Format.LeftIndent = leftindent + "cm";
        }

        public void AddText(Document document, string a, string b, int leftindent, bool header)
        {
            Section section = document.LastSection;


            if (!header)
            {
                Paragraph paragraph = section.AddParagraph();
                paragraph.Format.LeftIndent = leftindent + "cm";


                paragraph.AddText(a);

                paragraph.AddSpace((int)((40 - a.Length) * 1.9));

            }
            else
            {
                Paragraph paragraph = section.AddParagraph(a, "Heading2");
            }
        }

        public void AddText2(Document document, string a, int leftindent, bool header)
        {
            
            Section section = document.LastSection;
            Paragraph paragraph;
            if(header)
                paragraph = section.AddParagraph(a, "Heading2");
            else
                paragraph = section.AddParagraph(a, "Heading3");
            
            paragraph.Format.LeftIndent = leftindent + "cm";

            //paragraph.AddText(a);

            paragraph.AddSpace((int)((40 - a.Length) * 1.9));

        }

        public void AddTableOneLine(Document document, string title, string[] tableHeader, object[] tableContent)
        {
            Section section = document.LastSection;


            Paragraph paragraph = section.AddParagraph(title, "Heading2");


            Table table = new Table();
            table.Borders.Width = 0.75;

            for (int j = 1; j <= tableHeader.Length; j++)
            {
                Column column;

                column = table.AddColumn(Unit.FromCentimeter(26.00 / tableHeader.Length));

                column.Format.Alignment = ParagraphAlignment.Center;
            }


            Row row = table.AddRow();
            row.Shading.Color = Colors.PaleGoldenrod;
            int i = 0;
            Cell cell;
            foreach (string s in tableHeader)
            {
                cell = row.Cells[i++];
                row.Format.Font.Size = 8;
                cell.AddParagraph(s);
            }

            row = table.AddRow();
            i = 0;
            foreach (object s in tableContent)
            {
                cell = row.Cells[i++];
                row.Format.Font.Size = 8;
                cell.AddParagraph(s.ToString().Replace(',', ' '));
            }

            table.SetEdge(0, 0, tableHeader.Length, 2, Edge.Box, BorderStyle.Single, 0.75, Colors.Black);

            document.LastSection.Add(table);
        }

        public void AddTablesMultipleLines(Document document, string title, string[,] tableIntroduction, int tableIntroductionRows, string[] tableHeader, string[,] tableContent, int rows)
        {
            Section section = document.LastSection;

            section.AddPageBreak();

            Paragraph paragraph = section.AddParagraph(title, "Heading2");

            for (int i = 0; i < tableIntroductionRows; i++)
            {

                this.AddText(document, tableIntroduction[i, 0], tableIntroduction[i, 1], 0, false);

            }
            paragraph = section.LastParagraph;

            paragraph.Format.SpaceAfter = 15;


            Table table = new Table();
            table.Borders.Width = 0.75;

            for (int i = 1; i <= tableHeader.Length; i++)
            {
                Column column;
                column = table.AddColumn(Unit.FromCentimeter(26.00 / tableHeader.Length));
                column.Format.Alignment = ParagraphAlignment.Center;

                // Insert spaces in header items, in order to be able to split them across multiple lines
                //tableHeader[i] = tableHeader[i].InsertSpaces(5);
            }


            Row row = table.AddRow();
            row.Shading.Color = Colors.PaleGoldenrod;
            int index = 0;
            Cell cell;
            foreach (string s in tableHeader)
            {
                cell = row.Cells[index++];
                row.Format.Font.Size = 8;
                cell.AddParagraph(s);
            }




            for (int i = 0; i < rows; i++)
            {
                row = table.AddRow();
                row.Format.Font.Size = 8;
                index = 0;
                for (int x = 0; x < tableHeader.Length; x++)
                {

                    cell = row.Cells[index++];
                    tableContent[i, x] = tableContent[i, x].ToString().Replace(";", " ");
                    tableContent[i, x] = tableContent[i, x].ToString().Replace("/", "/ ");


                    cell.AddParagraph(tableContent[i, x]);
                }
            }
            table.SetEdge(0, 0, tableHeader.Length, rows + 1, Edge.Box, BorderStyle.Single, 0.75, Colors.Black);

            document.LastSection.Add(table);
        }

        public void AddInfos(Document document, Dictionary<string, string> dict)
        {
            Section section = document.LastSection;

            Table table = new Table();
            table.Borders.Width = 0;

            Column column;

            column = table.AddColumn(Unit.FromCentimeter(2));
            column = table.AddColumn(Unit.FromCentimeter(6));
            column.Format.Alignment = ParagraphAlignment.Left;
            column = table.AddColumn(Unit.FromCentimeter(6));
            column.Format.Alignment = ParagraphAlignment.Left;



            Row row;
            Cell cell;
            int index;

            foreach (KeyValuePair<string, string> pair in dict)
            {
                row = table.AddRow();
                row.Format.Font.Size = 10;

                index = 0;
                cell = row.Cells[index++];
                cell.AddParagraph("");
                cell = row.Cells[index++];
                cell.AddParagraph(pair.Key);
                cell = row.Cells[index++];
                cell.AddParagraph(pair.Value);

            }
            table.SetEdge(0, 0, 0, 0, Edge.Box, BorderStyle.Single, 0.75, Colors.Black);

            document.LastSection.Add(table);
        }

        public void DrawImage(XGraphics gfx, int number, string jpegSamplePath)
        {
            BeginBox(gfx, number, "DrawImage (original)");

            XImage image = XImage.FromFile(jpegSamplePath);

            // Left position in point
            double x = (250 - image.PixelWidth * 72 / image.HorizontalResolution) / 2;
            gfx.DrawImage(image, x, 0);

            EndBox(gfx);
        }

        public void BeginBox(XGraphics gfx, int number, string title)
        {/*
            const int dEllipse = 15;
            XRect rect = new XRect(0, 20, 300, 200);
            if (number % 2 == 0)
                rect.X = 300 - 5;
            rect.Y = 40 + ((number - 1) / 2) * (200 - 5);
            rect.Inflate(-10, -10);
            XRect rect2 = rect;
            rect2.Offset(document.borderWidth, document.borderWidth);
            gfx.DrawRoundedRectangle(new XSolidBrush(this.shadowColor), rect2, new XSize(dEllipse + 8, dEllipse + 8));
            XLinearGradientBrush brush = new XLinearGradientBrush(rect, this.backColor, this.backColor2, XLinearGradientMode.Vertical);
            gfx.DrawRoundedRectangle(this.borderPen, brush, rect, new XSize(dEllipse, dEllipse));
            rect.Inflate(-5, -5);

            XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
            gfx.DrawString(title, font, XBrushes.Navy, rect, XStringFormats.TopCenter);

            rect.Inflate(-10, -5);
            rect.Y += 20;
            rect.Height -= 20;

            this.state = gfx.Save();
            gfx.TranslateTransform(rect.X, rect.Y);*/
        }

        public void EndBox(XGraphics gfx)
        {
            /*
            gfx.Restore(this.state);*/
        }

        public void DrawTitle(Document document, PdfPage page, XGraphics gfx, string title)
        {
            XRect rect = new XRect(new XPoint(), gfx.PageSize);
            rect.Inflate(-10, -15);
            XFont font = new XFont("Verdana", 14, XFontStyle.Bold);
            gfx.DrawString(title, font, XBrushes.MidnightBlue, rect, XStringFormats.TopCenter);

            rect.Offset(0, 5);
            font = new XFont("Verdana", 8, XFontStyle.Italic);
            XStringFormat format = new XStringFormat();
            format.Alignment = XStringAlignment.Near;
            format.LineAlignment = XLineAlignment.Far;
            gfx.DrawString("Created with " + PdfSharp.ProductVersionInfo.Producer, font, XBrushes.DarkOrchid, rect, format);

            font = new XFont("Verdana", 8);
            format.Alignment = XStringAlignment.Center;
            //gfx.DrawString(document.PageCount.ToString(), font, XBrushes.DarkOrchid, rect, format);

            //document.Outlines.Add(title, page, true);
        }


       
    }

    public static class StringSpaces
    {
        public static String InsertSpaces(this String s, int continuousCharacters)
        {
            int index = 0;
            string newString = string.Empty;
            while (index < s.Length)
            {
                string substr = s.Substring(index, continuousCharacters);
                newString += substr + " ";
                index += continuousCharacters;
            }
            return newString;
        }
    }
}
